package zoltan.balog.solver.impl;

import java.util.HashMap;
import java.util.Map;

import zoltan.balog.entities.City;
import zoltan.balog.entities.Route;
import zoltan.balog.plan.IPlan;
import zoltan.balog.result.IResult;
import zoltan.balog.result.impl.Result;
import zoltan.balog.solver.ISolver;

public class GreedySolver implements ISolver {

	@Override
	public IResult solve(final IPlan plan) {
		final Map<Route, City> solution = new HashMap<Route, City>(plan.getNumOfRoutes());
		final double[] result = new double[plan.getNumOfCities()];
		
		initialize(plan, result);
		
		/*
		 * Calculate costs
		 */
		for (final Route route : plan.getRoutes()) {
			if (result[route.getFrom().getId()] <= result[route.getTo().getId()]) {
				//aggregate cost
				result[route.getFrom().getId()] += route.getCost();
				solution.put(route, route.getFrom());
			} else {
				result[route.getTo().getId()] += route.getCost();
				solution.put(route, route.getTo());
			}
		}
		return new Result(solution, plan);
	}

	private void initialize(final IPlan plan, final double[] result) {
		for (int i = 0; i < plan.getNumOfCities(); i++) {
			result[i] = 0.0;
		}
	}
}
